package com.terran4j.demo.swagger2;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

@RestController
@RequestMapping(value = "/users")
public class UserController {

    // 当作 id 生成器。
    private AtomicLong idCount = new AtomicLong(0);

    private Map<Long, User> users = new ConcurrentHashMap<Long, User>();

    @PostConstruct
    public void init() {
        addUser("刘备");
        addUser("关羽");
        addUser("张飞");
    }

    @ApiOperation(value = "创建用户", notes = "根据用户名创建用户")
    @ApiImplicitParam(name = "name", value = "用户名称",
            required = true)
    @RequestMapping(value = "", method = RequestMethod.POST)
    public User addUser(@RequestParam("name") String name) {
        long id = idCount.incrementAndGet();
        User user = new User(id, name);
        users.put(id, user);
        return user;
    }

    @ApiOperation(value = "获取用户列表", notes = "获取所有用户的列表")
    @RequestMapping(value = "", method = RequestMethod.GET)
    public List<User> getUsers() {
        return new ArrayList<User>(users.values());
    }

    @ApiOperation(value = "获取用户详细信息", notes = "根据url的id来获取用户详细信息")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public User getUser(@PathVariable Long id) {
        return users.get(id);
    }

    @ApiOperation(value = "更新用户名",
            notes = "根据url的id来指定更新用户名")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID",
                    required = true, dataType = "Long"),
            @ApiImplicitParam(name = "name", value = "用户名称",
                    required = true)
    })
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public void putUser(@PathVariable Long id, @RequestParam("name") String name) {
        users.get(id).setName(name);
    }

    @ApiOperation(value = "删除用户", notes = "根据url的id来指定删除对象")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public void deleteUser(@PathVariable Long id) {
        users.remove(id);
    }

}
